﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XNADash.Sound;

namespace XNADash.BoardBlocks
{
    public abstract class FallingBlock : BaseBlock
    {
        protected bool IsFalling = false;
        private int delayFallW = 0;
        private int delayFallE = 0;
        const int DELAYFALL = 2;

        public override void ApplyPhysics()
        {
            this.ExplodeIfMust();

            // czy pod spodem coś jest?
            BaseBlock block = this.GetNeighbour( Directions.S );
            if ( block == null )
            {
                // bezwarunkowe spadanie
                this.MoveTo( Directions.S );
                IsFalling = true;

                return;
            }
            else
            {
                // spadł na gracza
                if ( ( block is PlayerBlock || block is EnemyBlock ) && this.IsFalling )
                {
                    block.ExplodeNeighbour( Directions.None );
                    SoundFactory.Instance.RegisterEffect( SoundType.Bomb );
                }
                if ( block is BombBlock && this.IsFalling )
                {
                    ( (BombBlock)block ).Explode();
                    SoundFactory.Instance.RegisterEffect( SoundType.Bomb );
                }

                // stoi na "spadalnym"
                if ( block.OthersFallFrom )
                {
                    // może spaść w prawo - lewo?
                    if ( this.GetNeighbour( Directions.W ) == null &&
                         this.GetNeighbour( Directions.SW ) == null &&
                         ( this.GetNeighbour( Directions.NW ) == null || !this.GetNeighbour( Directions.NW ).CanBeLifted )
                        )
                    {
                        delayFallW++;

                        if ( delayFallW >= DELAYFALL )
                        {
                            this.MoveTo( Directions.W );
                            IsFalling = true;
                            delayFallW = delayFallE = 0;
                        }

                        return;
                    }
                    if ( this.GetNeighbour( Directions.E ) == null &&
                         this.GetNeighbour( Directions.SE ) == null &&
                         ( this.GetNeighbour( Directions.NE ) == null || !this.GetNeighbour( Directions.NE ).CanBeLifted )
                        )
                    {
                        delayFallE++;

                        if ( delayFallE >= DELAYFALL )
                        {
                            this.MoveTo( Directions.E );
                            IsFalling = true;
                            delayFallW = delayFallE = 0;
                        }

                        return;
                    }
                }
            }

            IsFalling = false;

            return;
        }

    }
}
